<?php

namespace Endor\EndorBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Endor\EndorBundle\Entity\Compras;
use Endor\EndorBundle\Form\ComprasType;
use Doctrine\Common\Collections\Collection;
use \Endor\EndorBundle\Entity\ItemsCompras;
use \Endor\EndorBundle\Entity\Entradas;
use \Endor\EndorBundle\Entity\Bodegas;

use Symfony\Component\HttpFoundation\Response;

include_once('bundles/EndorBundle/Plugins/MPDF54/mpdf.php');
/**
 * Compras controller.
 *
 */
class ComprasController extends Controller {

    /**
     * Lists all Compras entities.
     *
     */
    private function DeepLoad($entity) {
        $em = $this->getDoctrine()->getEntityManager();
        $items = $em->getRepository('EndorBundle:ItemsCompras')->findBy(array('Compra' => $entity->getId()));
        $entity->setItemsCompras($items);

        return $entity;
    }

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();

        $entities = $em->getRepository('EndorBundle:Compras')->findAll();

        return $this->render('EndorBundle:Compras:index.html.twig', array(
                    'entities' => $entities
                ));
    }

    /**
     * Finds and displays a Compras entity.
     *
     */
    public function showAction($id, $_format) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('EndorBundle:Compras')->find($id);
        $entity = $this->DeepLoad($entity);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Compras entity.');
        }

        if($_format == 'pdf'){
            $response = new Response();
            $response->headers->set('Content-Type', 'text/pdf');
            $response->send();
            
            $mpdf = new \mPDF('c','A4','','',32,25,100,25,16,13); 
            
            $mpdf->SetDisplayMode('fullpage');
            $mpdf->list_indent_first_level = 0;            
            
            $stylesheet = file_get_contents('bundles/EndorBundle/css/reports.css');
            $mpdf->WriteHTML($stylesheet,1);
            $mpdf->SetHTMLHeader($this->renderView('EndorBundle:ReportsFormat:entradas.header.html.twig',array('entity' => $entity)));            
            $mpdf->AddPage('L');
            $mpdf->WriteHTML($this->renderView('EndorBundle:ReportsFormat:entradas.html.twig',array('entity' => $entity)),2);
            $mpdf->setFooter('{PAGENO} de 1 paginas||{PAGENO} de 1 paginas');
            $content = $mpdf->Output();
            
            return $response;
        }else{        
            
             $deleteForm = $this->createDeleteForm($id);
             return $this->render('EndorBundle:Compras:show.html.twig', array(
                    'entity' => $entity,
                    'delete_form' => $deleteForm->createView(),
                ));
        }
    }

    /**
     * Displays a form to create a new Compras entity.
     *
     */
    public function newAction() {
        $entity = new Compras();
        $form = $this->createForm(new ComprasType(), $entity);
        $em = $this->getDoctrine()->getEntityManager();

        $articulos = $em->getRepository("EndorBundle:Articulos")->findAll();

        return $this->render('EndorBundle:Compras:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                    "articulos" => $articulos,
                ));
    }

    /**
     * Creates a new Compras entity.
     *
     */
    public function createAction() {
        $entity = new Compras();
        $request = $this->getRequest();
        $form = $this->createForm(new ComprasType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity->setFechaCreacion(date_create());
            $fechaRadicacion = $request->get("fechaRadicacion");
            $entity->setFecha(date_create($fechaRadicacion));
            $entity->setEstadoCompra($em->getRepository("EndorBundle:EstadosCompras")->find(6));
            $em->persist($entity);
            
            $array = $request->get("ItemsCompras", array());
            foreach ($array as $value) {
                $articulo = $em->find("EndorBundle:Articulos", $value["idArticulo"]);

                $item = new ItemsCompras();
                $item->setCompra($entity);
                $item->setArticulo($articulo);
                $item->setValor($value["valor"]);
                $item->setCantidad($value["cantidad"]);
                $item->setIsTipoUnidad($value["unidad"]);

                $em->persist($item);
            }

            $em->flush();
            return $this->redirect($this->generateUrl('compras_show', array('id' => $entity->getId())));
        }

        return $this->newAction();
    }

    /**
     * Displays a form to edit an existing Compras entity.
     *
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        /* @var $entity Compras */
        $entity = $em->getRepository('EndorBundle:Compras')->find($id);
        $entity = $this->DeepLoad($entity);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Compras entity.');
        }

        $editForm = $this->createForm(new ComprasType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $estadoCompra = $entity->getEstadoCompra()->getId();

        $articulos = array();

        if ($estadoCompra == 6) {
            $articulos = $em->getRepository("EndorBundle:Articulos")->findAll();
        }

        return $this->render('EndorBundle:Compras:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                    "articulos" => $articulos,
                ));
    }

    public function cambiarEstadoAction($idCompra, $idEstado) {
        $em = $this->getDoctrine()->getEntityManager();

        /* @var $entity Compras */
        $entity = $em->getRepository('EndorBundle:Compras')->find($idCompra);

        if ($entity->getEstadoCompra()->getId() == 6) {
            $entity->setEstadoCompra($em->getRepository('EndorBundle:EstadosCompras')->find($idEstado));
            $em->persist($entity);
            $em->flush();
        }
        return $this->redirect($this->generateUrl('compras'));
    }

    public function descargarAction($idCompra) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('EndorBundle:Compras')->find($idCompra);

        if ($entity->getEstadoCompra()->getId() == 1) {
            $itemsCompras = $em->getRepository('EndorBundle:ItemsCompras')->findBy(array(
                "Compra" => $idCompra
                    ));
            $bodegas = $em->getRepository('EndorBundle:Bodegas')->findBy(array(
                "habilitado" => 1
                    ));
            return $this->render('EndorBundle:Compras:descargar.html.twig', array(
                        'entity' => $entity,
                        'itemsCompras' => $itemsCompras,
                        'bodegas' => $bodegas
                    ));
        }

        return $this->redirect($this->generateUrl('compras'));
    }

    public function confirmarDescargaAction() {
        $em = $this->getDoctrine()->getEntityManager();

        $request = $this->getRequest();

        $idCompra = $request->get("idCompra");
        /* @var $compra Compras */
        $compra = $em->getRepository('EndorBundle:Compras')->find($idCompra);
        $compra->setEstadoCompra($em->getRepository('EndorBundle:EstadosCompras')->find(2));

        $items = $request->get("items");

        foreach ($items as $item) {
            if (array_key_exists("check", $item)) {
                $entrada = new Entradas();
                $itemCompra = new ItemsCompras();
                $bodega = new Bodegas();

                $itemCompra = $em->getRepository('EndorBundle:ItemsCompras')->find($item["idItemCompra"]);
                $bodega = $em->getRepository('EndorBundle:Bodegas')->find($item["bodega"]);
                $articulo = $em->getRepository('EndorBundle:Articulos')->find($item["articulo"]);

                //TODO: [debug] Borrar esta linea.
                echo is_null($articulo);

                $entrada->setArticulo($articulo);
                $entrada->setProveedor($itemCompra->getCompra()->getProveedor());
                $entrada->setItemCompra($itemCompra);
                $entrada->setBodega($bodega);
                $entrada->setCantidad($item["cantidad"]);


                $entrada->setFechaEntrada(date_create($item["fecha"]));
                $entrada->setFechaVencimiento(date_create($item["fechaVencimiento"]));

                $em->persist($entrada);
            }
        }

        $em->persist($compra);
        $em->flush();

        return $this->redirect($this->generateUrl("compras"));
    }

    /**
     * Edits an existing Compras entity.
     *
     */
    public function updateAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        /* @var $entity Compras */
        $entity = $em->getRepository('EndorBundle:Compras')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Compras entity.');
        }

        $editForm = $this->createForm(new ComprasType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();
        $fechaRadicacion = $request->get("fechaRadicacion");
        $entity->setFecha(date_create($fechaRadicacion));

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            $itemsChanges = $request->get("ItemsCompras");

            if (!is_null($itemsChanges) && count($itemsChanges) > 0) {
                foreach ($itemsChanges as $value) {
                    if ($value["status"] == "New" || $value["status"] == "Modified") {
                        
                        if ($value["status"] == "New") {
                            $item = new ItemsCompras();
                            $articulo = $em->find("EndorBundle:Articulos", $value["idArticulo"]);
                            
                            $item->setCompra($entity);
                            $item->setArticulo($articulo);
                        } else {
                            $item = $em->find("EndorBundle:ItemsCompras", $value["id"]);
                        }

                        $item->setValor($value["valor"]);
                        $item->setCantidad($value["cantidad"]);
                        $item->setIsTipoUnidad($value["unidad"]);

                        $em->persist($item);
                    } else if ($value["status"] == "Removed") {
                        $item = $em->find("EndorBundle:ItemsCompras", $value["id"]);
                        $em->remove($item);
                    }
                }
            }

            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('compras_show', array('id' => $id)));
        }

        return $this->render('EndorBundle:Compras:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    /**
     * Deletes a Compras entity.
     *
     */
    public function deleteAction($id) {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('EndorBundle:Compras')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Compras entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('compras'));
    }

    private function createDeleteForm($id) {
        return $this->createFormBuilder(array('id' => $id))
                        ->add('id', 'hidden')
                        ->getForm()
        ;
    }

}
